<template>
  <el-dialog :model-value="visible" width="550px" title="添加员工" @close="handleClose" :fullscreen="mobile" class="dialog-content-clear">
    <el-alert title="新增员工后，系统会给员工的手机号或邮箱发送一条开通账号短信通知" type="warning" :closable="false" />
    <div class="ph-16 mt20">
      <el-form :model="staffForm" ref="staffFormRef" :rules="staffFormRules" label-width="120px">
        <el-form-item label="姓名" prop="companyUserName">
          <el-input v-model="staffForm.companyUserName" placeholder="请输入员工姓名" style="width: 80%;"></el-input>
        </el-form-item>
        <el-form-item label="登录账号" prop="account">
          <el-input v-model="staffForm.account" placeholder="请输入手机号或邮箱" style="width: 80%;"></el-input>
        </el-form-item>
        <el-form-item label="员工岗位" prop="roleId">
          <el-select v-model="staffForm.roleId" @change="handleRoleIdChange">
            <el-option :label="item.name" :value="item.roleId" v-for="item in roleOptions" :key="item.roleId" />
          </el-select>
        </el-form-item>
        <el-form-item label="查看入住人" prop="lookAllCheckInRecordsFlag">
          <el-select v-model="staffForm.lookAllCheckInRecordsFlag">
            <el-option label="查看所有入住人信息" :value="1" />
            <el-option label="仅自己办理的入住人信息" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="分组" prop="group">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
        </el-form-item>
        <el-form-item>
          <el-checkbox-group
            v-model="staffForm.group"
            @change="handleCheckedChange"
            style="width: 100%;"
          >
            <el-row >
              <el-col :span="10" v-for="group in groupList" :key="group.value">
                <el-checkbox
                  :label="group.value"
                  >{{ group.label }}</el-checkbox
                >
              </el-col>
            </el-row>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleOk">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup name="StaffOperationDl">
import useAppStore from '@/store/modules/app'
import group from '@/api/setting/group'
import { deepClone } from '@/utils'


const { proxy } = getCurrentInstance()

const emit = defineEmits()
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  type: {
    type: String,
    default: 'add'
  },
  form: {
    type: Object,
    default: () => {}
  }
})
const mobile = computed(() => useAppStore().device === 'mobile')
watch(() => props.visible, (value) => {
  if (value) {
    proxy.resetForm('staffFormRef')
    checkAll.value = false
    isIndeterminate.value = true
    if (props.type === 'edit') {
      staffForm.value = deepClone(props.form)
    }
  }
})

const validatePass = (rule, value, callback) => {
  if (value.length === 0) {
    callback(new Error('请选择分组'))
  } else {
    if (staffForm.value.group !== '') {
      if (!proxy.$refs['staffFormRef']) return
      proxy.$refs['staffFormRef'].validateField('group', () => null)
    }
    callback()
  }
}

const checkAll = ref(false)
const isIndeterminate = ref(true)
const groupList = ref([])
const roleOptions = ref([{
  roleId: 1,
  name: '管理员'
}, {
  roleId: 2,
  name: '设备管理'
}, {
  roleId: 3,
  name: '安装'
}, {
  roleId: 4,
  name: '房间管理'
}, {
  roleId: 5,
  name: '入住管理'
}, {
  roleId: 6,
  name: '保洁'
}])

const data = reactive({
  staffForm: {
    companyUserName: null,
    account: null,
    roleId: null,
    lookAllCheckInRecordsFlag: 1,
    group: []
  },
  staffFormRules: {
    companyUserName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    account: [
      { required: true, trigger: 'blur', message: '请输入手机号或邮箱' },
      { pattern: /^(1[3|4|5|6|7|8|9][0-9]\d{8}$)|(\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$)/, message: '请输入手机号或邮箱', trigger: 'blur', }
    ],
    roleId: [{ required: true, message: '请选择', trigger: 'change' }],
    lookAllCheckInRecordsFlag: [{ required: true, message: '请选择', trigger: 'blur' }],
    group: [
      { required: true, message: '请选择分组', trigger: 'blur' },
      { validator: validatePass, trigger: 'blur' }
    ]
  }
})
const { staffForm, staffFormRules } = toRefs(data)

/* 分组全选按钮 */
function handleCheckAllChange(val) {
  console.log(groupList.value.map(item => item.value));
  staffForm.value.group = val ? groupList.value.map(item => item.value) : []
  isIndeterminate.value = false
}
/* 分组 按钮组发生变化 */
function handleCheckedChange(value) {
  console.log(staffForm.value.group);
  const checkedCount = value.length
  checkAll.value = checkedCount === groupList.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < groupList.value.length
}

/* 岗位下拉选择发生变化 */
function handleRoleIdChange(value) {
  let index = roleOptions.value.findIndex(item => item.roleId === value)
  if (index !== -1) staffForm.value.roleName = roleOptions.value[index].name
}

function handleClose() {
  emit('cancel')
}

function handleOk() {
  proxy.$refs["staffFormRef"].validate(valid => {
    if (valid) {
      emit('ok', staffForm.value)
    }
  }) 
}

// 获取分组列表
function getGroupList() {
  group.getList().then(res => {
    groupList.value = res.rows.map(item => ({
      label: item.groupName,
      value: item.groupId
    }))
    staffForm.value.groupId = groupList.value[0].value
  })
}
getGroupList()
</script>
<style lang="scss" scoped>
.dialog-content-clear {
  .el-form-item--default {
    margin-bottom: 18px;
  }
}
</style>